package research.dao.hibernate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import research.dao.IEntityDAO;
import research.entity.Entity;
import research.entity.EntityType;
import research.model.IHierarchyProvider;
import research.persistence.IPersistenceDataSource;
import research.persistence.IPersistenceListener;

public class HibernatePersistance implements IPersistenceDataSource, IPersistenceListener {
	
	private IEntityDAO getDAO() {
		return new HibernateDAO();
	}

	@Override
	public Entity get(EntityType type, long id) {
		return getDAO().get(type.getEntityClass(), id, false);
	}

	@Override
	public <T extends Entity> List<T> getAll(EntityType type) {
		return getConvertedList(getDAO().getAll(type.getEntityClass()));
	}
	
	@Override
	public List<Entity> getChildren(Entity entity,
			IHierarchyProvider hierarchy) {
		return getDAO().getChildren(entity, hierarchy);
	}

	@Override
	public Entity getParent(Entity entity,
			IHierarchyProvider hierarchy) {
		return getDAO().getParent(entity, hierarchy);
	}
	
	@Override
	public void add(Entity entity) {
		getDAO().makePersistent(entity);
	}

	@Override
	public void remove(Entity entity) {
		getDAO().makeTransient(entity);
	}

	@Override
	public void update(Entity entity) {
		getDAO().makePersistent(entity);
	}

	@Override
	public boolean isPersistent(Entity entity) {
		return entity.getId() >= 0;
	}	
	
	@SuppressWarnings("unchecked")
	public static <T extends Entity>  List<T> getConvertedList(Collection<Entity> data) {
		List<T> res = new ArrayList<T>();
		for (Entity entity : data) {
			T item = (T) entity;
			res.add(item);
		}
		return res;
	}

}
